'use strict';

$( document ).ready(function() {
// Handler for .ready() called.

    $(window).resize(function(){
        $('.ui-fancytree').each(function(){
            $(this).css('max-height', $(window).height()-210);
        });

        $('.firetable').each(function(){
            $(this).css('max-height', $(window).height()-153);
        })

        $('#splitter-bar').each(function(){
            $(this).css('height', $("#left_area").height()-62);
        })
    });

});



var app = angular.module('fireProtectionApp')
    .config(function (cfpLoadingBarProvider) {
        cfpLoadingBarProvider.includeSpinner = true;
    })


    .service('dataService', ['$http', '$rootScope', function ($http, $rootScope) {

    this.appVo = new AppVO();

    /* F4 Help */
    this.getF4Help = function (iobjnm, vname, queryName) {
        var param = {
            iobjnm:iobjnm,
            vname:vname,
            queryName:queryName
        };
        return   $http({method:this.appVo.METHOD, url:this.appVo.BSP_GET_F4_URL, params:param});
    }

    this.getVarList = function (queryName) {
        var param = {
            rep_id:queryName
        };
        return  $http({method:this.appVo.METHOD, url:this.appVo.BSP_QUERY_VARS_LIST_URL, params:param});
    }


    this.executeQuery = function (param) {
            return $http({method:this.appVo.METHOD, url:this.appVo.BSP_QUERY_EXECUTE_URL, params:param});
    }

    this.getOrgTree = function (param) {
        var param = {};
        return $http({method:this.appVo.METHOD, url:this.appVo.BSP_ORG_TREE_URL});
    }

    this.exportToExcel = function (param) {
        return $http({method:this.appVo.METHOD, url:this.appVo.BSP_ORG_TREE_URL});
    }

    this.getComponentsList = function () {
        return $http({method:this.appVo.METHOD, url:this.appVo.COMPONENTS_LIST_URL});
    }

    $rootScope.$on('TREE_NODE_SELECTED_EVENT', function (event, data) {
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT", data);
    });

    $rootScope.$on('YEAR_HAS_BEEN_SELECTED_EVENT', function (event, data) {
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT", data);
    });

    $rootScope.$on('QUARTER_HAS_BEEN_SELECTED_EVENT', function (event, data) {
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT", data);
    });

    $rootScope.$on('SET_DEFAULT_YEAR_QUARTER_EVENT', function (event, data) {
        $rootScope.$broadcast("UPDATE_DEFAULT_YEAR_QUARTER_EVENT", data);
    });

    $rootScope.$on('EXPORT_EXCEL_EVENT', function (event, data) {
        $rootScope.$broadcast("EXPORT_EXCEL_HANDLER_EVENT", data);
    });


}])
    .service('mockHelperService', [function ($rootScope) {


    this.generateReportVariableParam = function (query, org, year, quarter, isLeaf) {
        var result = {};
        var counter = 1;
        var tmp = '';
        if (quarter != '') {
            tmp += '&VAR_NAME_' + counter + '=' + 'Z_X_QUART';
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + quarter;
            counter++;
        }

        if (org != "") {
            tmp += '&VAR_NAME_' + counter + '=' + this.getOrgName(isLeaf);
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + org;
            if (!isLeaf)
                tmp += '&VAR_NODE_IOBJNM_' + counter + '=' + '0ORGUNIT';
            counter++;
        }

        if (year != '') {
            tmp += '&VAR_NAME_' + counter + '=' + 'ZEX_PDT_YEAR';
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + year;
        }

        result['variables'] = encodeURI(tmp);
        result['query'] = this.getQueryName(isLeaf);


        return result;
    }

    this.getOrgName = function(isLeaf) {
        if(isLeaf)
            return "ZFIRE_ORG";
        else
            return "Z_X_FORG";

    }

    this.getQueryName = function(isLeaf) {
        if(isLeaf)
            return FRDB_QUERY_NAME_FOR_LEAF;
        else
            return FRDB_QUERY_NAME;
    }
}])

    .controller('MainCtrl', function ($scope, dataService, cfpLoadingBar) {
        /* Show Loading Bar */
        $scope.start = function () {
            cfpLoadingBar.start();
        };
        /* Hide Loading Bar */
        $scope.complete = function () {
            cfpLoadingBar.complete();
        }



        /* HTTP: OK -- Parse: OK */
        $scope.executeQuery = function (queryName, variables) {
            //Show Loading Bar
            $scope.start();

            dataService.executeQuery(queryName, variables)
                .success(function (data) {
                    $scope.complete();
                    /* $timeout(function() {
                     $scope.complete();
                     }, 1000);*/

                    $scope.status = status;
                    $scope.data = data;
                    $scope.reportVo = (new ReportVO(data)).parse();

                })
                .error(function (error) {
                    //Stop loading Bar
                    $scope.complete();
                    $scope.status = 'Unable to load query data: ' + error.message;
                    $scope.data = data;
                });
        };


        /* HTTP: OK -- Parse: OK */
        $scope.getF4Help = function (iobjnm, vname, queryName) {
            dataService.getF4Help(iobjnm, vname, queryName).
                success(
                function (data, status) {
                    $scope.status = status;
                    $scope.data = $.xml2json(data);
                    $scope.varList = new F4VOList($scope.data);
                }).
                error(function (data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };

        /* Ok*/
        $scope.getVarList = function (queryName) {
            dataService.getVarList(queryName).
                success(
                function (data, status) {
                    $scope.status = status;
                    $scope.data = $.xml2json(data);
                }).
                error(function (data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };


        $scope.getOrgTree = function () {
            dataService.getOrgTree().
                success(
                function (data, status) {
                    $scope.status = status;
                    $scope.data = data;
                }).
                error(function (data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };


    })


    .controller('TreeCtrl', ['$scope', '$rootScope', 'dataService', 'cfpLoadingBar', function ($scope, $rootScope, dataService, cfpLoadingBar) {
    $scope.searchText = "";
    $scope.selectedNode = "";


    $scope.$watch('selectedNode', function (newVal, oldVal) {
        console.log('selected node: ' + newVal);
    });

    $scope.$watch('searchText', function (newVal, oldVal) {
        if (newVal !== "") {
            $("#treeFilterIcon").css("color", "mediumseagreen");
        }
        else {
            $("#treeFilterIcon").css("color", "darkgrey");
            if( $scope.dataProvider !== undefined)
            {
                $scope.resetDataProvider();
            }
        }

    });

    $scope.clearFilter2 = function () {
        $("button#btnResetSearch").click();
        $("#treeFilterIcon").css("color", "darkgrey");
        if( $scope.dataProvider !== undefined)
        {
            $scope.resetDataProvider();
        }
    }

   $scope.resetDataProvider = function() {
       $("#tree").fancytree("option", "source", angular.copy($scope.dataProvider));
   }



    /* Show Loading Bar */
    $scope.start = function () {
        cfpLoadingBar.start();
    };
    /* Hide Loading Bar */
    $scope.complete = function () {
        cfpLoadingBar.complete();
    }

    $scope.treeHasBeenLoaded  = false;
    $scope.start();
    /* Load Org Tree*/
    dataService.getOrgTree().
        success(
        function (data, status) {
            $scope.complete();
            $scope.NoAuthorizedState(true);
            $scope.status = status;
            $scope.data = data;
            $scope.dataProvider = data;
            $scope.buildTree(data);
            $scope.treeHasBeenLoaded = true;
        }).
        error(function (data, status) {
            $scope.complete();
            $scope.NoAuthorizedState(false);
            $scope.data = data || "Request failed";
            $scope.status = status;


        });


    $scope.NoAuthorizedState = function(enable) {
        if(!enable)
        {
            $("input[name=search]").val("[Not Auhtorized]");
            $("input[name=search]").attr("disabled", true);
            $("button#btnResetSearch").attr("disabled", true);
        }
        else
        {
            $("input[name=search]").val("");
            $("input[name=search]").attr("disabled", false);
            $("button#btnResetSearch").attr("disabled", false);
        }

    }

    $scope.buildTree = function (dataProvider) {
        var fancyTreeHelper = new FancyTreeHelper($rootScope, $scope, dataProvider);
        fancyTreeHelper.BuildTree();
    }

}])
    .controller('ControlBarCtrl', function ($scope, $rootScope, dataService, $filter, ngTableParams) {
        var currentYear = (new Date).getFullYear();
        var currentMonth = (new Date).getMonth();
        var currentQuarter = Math.floor(((currentMonth + 11) / 3) % 4) + 1;

        $scope.year = currentYear;
        $scope.quarter = currentQuarter;

        $scope.$watch('quarter', function (newVal, oldVal) {
            $scope.radioModel = 'Q' + newVal;
        });


        $scope.exportExcel_BtnClick = function () {
            $rootScope.$broadcast("EXPORT_EXCEL_EVENT");
        }


        /* GETTING Year List */
        dataService.getF4Help('0CALYEAR', 'ZEX_PDT_YEAR', 'ZFIRE_PROTECTION_DEPT_KPI').
            success(
            function (data, status) {
                $scope.status = status;
                $scope.data = $.xml2json(data);
                $scope.yearList = new F4VOList($scope.data);

                /* Set Default Year */
                if ($scope.yearList != 'undefined' && $scope.yearList.length > 1) {

                    //Sending updates to Main Controller
                    $scope.setDefaultYearQuarter($scope.year, $scope.quarter);


                    $scope.tableParams = new ngTableParams({
                        page:1, // show first page
                        count:999999999999, // count per page
                        filter:{
                            // name: 'M'       // initial filter
                        }
                    }, {
                        counts:[],
                        total:$scope.yearList.length, // length of data
                        getData:function ($defer, params) {
                            // use build-in angular filter
                            var orderedData = params.filter() ?
                                $filter('filter')($scope.yearList, params.filter()) :
                                data;
                            $scope.users = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
                            params.total(orderedData.length); // set total for recalc pagination
                            $defer.resolve($scope.users);
                        }
                    });
                }

            }).
            error(function (data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });


        /* Year has been changed */
        $scope.setSelectedYear = function (year) {
            if (year != "") {
                $scope.year = year;
                $rootScope.$broadcast("YEAR_HAS_BEEN_SELECTED_EVENT", {quarter:$scope.quarter, year:$scope.year});
            }
        }

        /* Quarter has been changed */
        $scope.setSelectedQuarter = function (item, $event) {
            var selectedQuarter = $($event.target).val();
            if (selectedQuarter !== $scope.quarter) {
                $scope.quarter = selectedQuarter;
                $rootScope.$broadcast("QUARTER_HAS_BEEN_SELECTED_EVENT", {quarter:$scope.quarter, year:$scope.year});
            }
        }

        /* Set Default Year  and Quarter */
        $scope.setDefaultYearQuarter = function (year, quarter) {
            $rootScope.$broadcast("SET_DEFAULT_YEAR_QUARTER_EVENT", {quarter:$scope.quarter, year:$scope.year});
        }


        $('.dropdown-menu').find('form').click(function (e) {
            e.stopPropagation();
        });


    })
    .controller('tablectrl', function ($scope, $rootScope, $filter, Report, AppSetting, ngTableParams, dataService, mockHelperService, $compile) {

        $scope.year = "";
        $scope.quarter = "";
        $scope.orgKey = "";
        $scope.showOrgKey = false;



        $scope.clearTable = function(id){
            $(id).html('');
        }

        $scope.clearRows = function () {
            $scope.rows = [];
            $scope.isCollapsed = true;
        }

        $scope.tableHeaderClick = function(group, groups) {
            //group.$hideRows = !group.$hideRows;
            /* Close All Headers */
            for (var i = 0; i < groups.length; i++) {
                if(groups[i].value !== group.value)
                    groups[i].$hideRows = false;
            }
            group.$hideRows = !group.$hideRows;


            $('.firetable').each(function(){
                $(this).css('max-height', $(window).height()-153);
            });

            $('#splitter-bar').each(function(){
                $(this).css('height', $("#left_area").height()-62);
            })
        }

        $scope.$on('EXPORT_EXCEL_HANDLER_EVENT', function (event, data) {

            var selectedColumns = ['ZEHFIRKPI_TXT', 'target', 'VALUE001'];
            var variablesList =
                [
                    {label:'Year', values:[$scope.year ]},
                    {label:'Quarter', values:[$scope.quarter]},
                    {label:'Organization', values:[ $scope.orgText]}
                ];

            var excelHelper = new ExcelExportHelper($scope.reportVo, selectedColumns, variablesList);
            var excelHTML = excelHelper.generateExcel();

            if(excelHTML != '')
                excelHelper.openWindowWithPost('ExcelForm', excelHTML, 'org_' + $scope.orgKey);
        });


        $scope.$on('UPDATE_DEFAULT_YEAR_QUARTER_EVENT', function (event, data) {
            $scope.year = data.year;
            $scope.quarter = data.quarter;
        });


        $scope.$on('EXECUTE_REPORT_EVENT', function (event, data) {

            $scope.isLeaf = true;
            if (data != 'undefined') {
                if (data.hasOwnProperty('year'))
                    $scope.year = data.year;
                if (data.hasOwnProperty('quarter'))
                    $scope.quarter = data.quarter;
                if (data.hasOwnProperty('orgKey'))
                    $scope.orgKey = data.orgKey;
                if (data.hasOwnProperty('isLeaf'))
                    $scope.isLeaf = data.isLeaf;
                if (data.hasOwnProperty('orgText'))
                    $scope.orgText = data.orgText;
            }


            var param = mockHelperService.generateReportVariableParam('ZCFIREP/ZFIRE_PROTECTION_DEPT_KPI',
                $scope.orgKey, $scope.year, $scope.quarter, $scope.isLeaf);

            $scope.rows = [];
            $scope.groupsList = [];

            $scope.clearRows();



            getComponentsList(param);
        });


        $scope.rows = [];
        $scope.groupsList = [];
        $scope.componentsList;
        $scope.groupby = 'ZFIRCOMP';//'ZEHFIRKPI__ZEHFIRKPI_KEY';




         /* Getting Component List */
        var getComponentsList= function(param) {
            if( $scope.componentsList === undefined)
            {
                dataService.getComponentsList()
                    .success(function (data){
                        var jsonData = $.xml2json(data);
                        console.log(jsonData);
                        var compVo = new ComponentVo(jsonData);
                        compVo.parse();
                        $scope.componentsList = compVo.componentsList;

                        /* Executing Query */
                        executeQuery(param);

                    })
                    .error(function (error) {
                        console.log('getComponentsList: ' + error);
                    })
            }

            else
                executeQuery(param);
        }
        /* Executing Query */
        var executeQuery = function (param) {

            $scope.rows = [];
            $scope.groupsList = [];
            $scope.clearTable('#myTableContainer');


            dataService.executeQuery(param)
                .success(function (data) {
                    if(data.report.error !== "")
                    {
                        alert(data.report.error)
                        $scope.reportVo = undefined;
                    }

                    else
                    {
                        var reportVo = new ReportVO(data,angular.copy($scope.componentsList));
                        reportVo.parse();
                        $scope.reportVo = reportVo;
                        //$scope.rows = $scope.reportVo.rows;
                        $scope.rows = $scope.reportVo.rowsFull;
                    }

                    $scope.status = status;
                    $scope.data = data;

                    if ($scope.orgKey != "")
                        $scope.showOrgKey = true;
                    else
                        $scope.showOrgKey = false;


                 //   $scope.groupsList = $scope.reportVo.fullComponentsList ;
              /*      $scope.groupsListFull =  reportVo.GetMergedGroups($scope.reportVo.groupedList, $scope.componentsList);*/

                    // Recompile the table
                    $.get('views/tablePartial.html', function(data)
                    {
                        $('#myTableContainer').html( $compile(data)($scope)
                        );


                    });



                    $scope.$watch('rows', function (newVal, oldVal) {

                        //dinamic grouping
                        $scope.tableParams = new ngTableParams({
                            page:1, // show first page
                            count:-1,        // count per page
                            sorting: {
                                name: 'asc'     // initial sorting
                            }

                        }, {
                            counts:[], // hide page counts control
                            groupBy:$scope.groupby,
                            total:function () {
                                return $scope.rows.length;
                            }, // length of data
                            getData:function ($defer, params) {
                                var orderedData = params.sorting() ?
                                    $filter('orderBy')($scope.rows, $scope.tableParams.orderBy()) : $scope.rows;

                                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                            }
                        });
                    });


                })
                .error(function (error) {
                    $scope.status = 'Unable to load query data: ' + error.message;
                });
        }

        $scope.getGroupText = function (id, groupsList) {
            var result = "";
            if(groupsList !== undefined)
            {
                for (var i = 0; i < groupsList.length; i++) {
                    if (id == groupsList[i].id) {
                        return groupsList[i].text;
                        break;
                    }
                }
            }
            return result;
        }

        $scope.getGroupValue = function (id, groupsList) {
            var result = "";
            if(groupsList !== undefined)
            {
                for (var i = 0; i < groupsList.length; i++) {
                    if (id == groupsList[i].id) {
                        result  =  groupsList[i].value === undefined? '' : groupsList[i].value;
                        break;
                    }
                }
                return result;
            }

        }

        $scope.getGroupTarget = function (id, groupsList) {
            if(groupsList !== undefined)
            {
                for (var i = 0; i < groupsList.length; i++) {
                    if (id == groupsList[i].id) {
                        return groupsList[i].target;
                        break;
                    }
                }
            }
            return '';
        }


        $scope.checkIfOrgSelected = function () {
            if ($scope.orgKey == '')
                return false;
            else
                return true;
        }

 


        /* Collapse / Expand Left Nav Tree*/
        $scope.leftTreeToggleCollapse = function () {

            var left = $(".split-pane2").css('left');

              if($("#collapseIcon").attr('class') === "glyphicon glyphicon-chevron-left")
              {
                  $("#left_area").hide();
                  $("#splitter-bar").hide();
                  $(".split-pane2").css('left', '18px');
                  $("#collapseIcon").attr('class', 'glyphicon glyphicon-chevron-right');
              }

              else
              {
                  var width = $("#left_area").css('width');
                  $("#left_area").show();
                  $("#splitter-bar").show();
                  $(".split-pane2").css('left', width) ;
                  $("#collapseIcon").attr('class', 'glyphicon glyphicon-chevron-left');
              }
        }

            /* Show Equations*/
            $scope.isCollapsed = true;
        $scope.openedFormula = '';
        $scope.showEquation = function(target, componentID, componentName) {
            $('#formulaContainer').css('visibility', 'visible');
            $scope.IMAGE_SRC  = "images/formulas/" + componentID + ".png";
            $scope.NAME = componentName;
            if(componentID != $scope.openedFormula)
                $scope.isCollapsed = false;
            else
                $scope.isCollapsed = !$scope.isCollapsed;

            $scope.openedFormula = componentID;
        }

    })
    .controller('EquationsController', function ($scope) {
        $('#list').click(function (event) {
            event.preventDefault();
            $('#products .item').addClass('list-group-item');
        });
        $('#grid').click(function (event) {
            event.preventDefault();
            $('#products .item').removeClass('list-group-item');
            $('#products .item').addClass('grid-group-item');
        });
    })

    .controller('ThemeController', function ($scope) {
        $scope.colorsList =
            [
                { title:"Pale Worm Brown", bgColor:"rgb(198, 156, 109)", class:"", color:"#c69c6d" },
                { title:"Medium Warm Brown", bgColor:"rgb(140, 98, 57)", class:"", color:"#8c6239" },
                { title:"Pale Cool Brown", bgColor:"rgb(199, 178, 153)", class:"", color:"#c7b299" },
                { title:"Pure Cyan", bgColor:"rgb(102, 199, 235)", class:"", color:"rgb(102, 199, 235)"},
                { title:"Pure Green", bgColor:"rgb(0, 166, 81)", class:"", color:"#00a651"},
                { title:"Pure Green Cyan", bgColor:"rgb(0, 169, 157)", class:"", color:"#00a99d"},
                { title:"Pure Pea Green", bgColor:"rgb(141, 198, 63)", class:"", color:"#8dc63f"},
                { title:"Orange", bgColor:"rgb(241, 176, 72)", class:"", color:"rgb(241, 176, 72)"},
                { title:"Light Red", bgColor:"rgb(219, 124, 128)", class:"", color:"rgb(219, 124, 128)"},
                { title:"Light Violet", bgColor:"rgb(166, 164, 202)", class:"", color:"#A6A4CA"},
                { title:"Grey 5%", bgColor:"rgb(245, 245, 245)", class:"light", color:"rgb(245,245,245)"},
                { title:"Grey 20%", bgColor:"rgb(215, 215, 215)", class:"light", color:"rgb(215, 215, 215)"},
                { title:"Grey 40%", bgColor:"rgb(172, 172, 172)", class:"", color:"rgb(172, 172, 172)"},
                { title:"Grey 60%", bgColor:"rgb(125, 125, 125)", class:"", color:"rgb(125, 125, 125)"},
                { title:"Grey 70%", bgColor:"rgb(99, 99, 99)", class:"", color:"rgb(99, 99, 99)"},
                { title:"Grey 80%", bgColor:"rgb(70, 70, 70)", class:"", color:"rgb(70, 70, 70)"},
                { title:"Grey 85%", bgColor:"rgb(54, 54, 54)", class:"", color:"rgb(54, 54, 54)"},
                { title:"Grey 90%", bgColor:"rgb(37, 37, 37)", class:"", color:"rgb(37, 37, 37)"}
            ];

        $scope.setBackgroundColor = function (color) {
            return {'background-color':color}
        }

        $scope.setBackGroundColor = function (colorList) {
            $('body').css("background-color", colorList.color);
            if (color.class == "light") {
                $('body').css("color", "#000000");
            }

        }
    })


    ;


